import ConfigParser
import getopt
import os
import logging,logging.config
import string
import sys
from os import path

class Config:
	app_name                         = 'malware-inspector'
	current_path                     = None
	action                           = None # remember the last action in case it fails
	config_file                      = ''
	log_level                        = logging.ERROR # only log errors by default
	logger                           = None
	logger_syslog                    = None
	logging_config                   = ''
	team_cymru_url                   = ''
	virustotal_url                   = ''
	virustotal_api_key               = '' 
	proxy_host			 = ''
	proxy_port                       = ''
	proxy_user                       = ''
	proxy_password                   = ''	
	use_proxy                        = False
	use_cymru_database               = True
	use_virustotal_database          = True  
	malware_results_database         = 'malware_inspector.db' 
	polling_interval                 = 0.25
	timeout_interval                 = 10
	email_server                     = ''
	email_port                       = ''
	email_user                       = ''
	email_passwd                     = ''
	run_every_minutes                = 5
	results_file                     = os.getcwd() + '/malware_results.txt"

	def __dir_exists(self,f):
		d = os.path.dirname(f)
		if not os.path.exists(d):
	            os.makedirs(d)
	def __init__(self):
		try:
	            self.__parseArgs()
	            self.__setupLogging()
	        except Exception, exception:
	            print "Errors in reading/parsing configuration files in %s directory: %s" % (os.getcwd() + '/etc', str(exception).strip())
	            sys.exit(1)

	def __readConfig(self, configfile):
	        "Read configuration file"
	        conf = ConfigParser.ConfigParser()
	        conf.read(configfile)
	        # save config. file name for internal use
	        self.config_file=configfile
	        #app-name
	        self.app_name = self.__confGet(conf, "general", "name") or self.app_name
	        #logging
	        self.log_level = self.__confGet(conf, "general", "log_level") or self.log_level
	        # find current path
	        self.current_path = path.abspath(path.dirname(__file__))
	
	        self.logging_config = self.current_path + "/.." + self.__confGet(conf,"general","logging_config_file") or self.logging_config
        
	        # proxy status
	        self.use_proxy = self.__confGet(conf,"general","use_proxy") or self.use_proxy

		# use team cymru and virustotal malware database or not
	        self.use_cymru_database = self.__confGet(conf,"general","use_cymru_database") or self.use_cymru_database
	        self.use_virustotal_database = self.__confGet(conf,"general","use_virustotal_database") or self.use_virustotal_database

		# run script every x minutes
	        self.run_every_minutes = self.__confGet(conf,"general","run_every_minutes") or self.run_every_minutes

	        # malware results database
	        self.malware_results_database = self.__confGet(conf,"general","db_file") or self.malware_results_database
		self.results_file = self.__confGet(conf,"general","results_file") or self.results_file
	        if os.path.exists(self.logging_config)==False:
        	    print "It seems that configuration file path for logging information is in-valid. Kindly correct it and try again."
        	    sys.exit(1)

		# team cymru base url, virus total urls and virus total api key
		self.team_cymru_url = self.__confGet(conf,"malware_links","team_cymru_url") or self.team_cymru_url
		self.virustotal_url = self.__confGet(conf,"malware_links","virustotal_url") or self.virustotal_url
	        self.virustotal_api_key = self.__confGet(conf,"malware_links","virustotal_api_key") or self.virustotal_api_key
		        	
		# proxy configuration
	        self.proxy_host = self.__confGet(conf,"proxy","host") or self.proxy_host
        	self.proxy_port = self.__confGet(conf,"proxy","port") or self.proxy_port
        	self.proxy_user = self.__confGet(conf,"proxy","user") or self.proxy_user
        	self.proxy_password = self.__confGet(conf,"proxy","password") or self.proxy_password

		
		# e-mail server configuration
		self.email_server = self.__confGet(conf,"mail","server") or self.email_server
		self.email_port = self.__confGet(conf,"mail","port") or self.email_port
		self.email_user = self.__confGet(conf,"mail","user") or self.email_user
		self.email_passwd = self.__confGet(conf,"mail","password") or self.email_passwd

		# process polling intervals
		self.timeout_interval = self.__confGet(conf,"process","timeout_interval") or self.timeout_interval
		self.polling_interval = self.__confGet(conf,"process","polling_interval") or self.polling_interval
    
	def __confGetSection(self, conf, section):
		"""returns the value of all the configuration options in one section or None if not set"""
        	try:
	            options = {}
	            for i in conf.items(section):
	                options [i[0]] = i[1]
	            return options
	        except ConfigParser.Error:
	            return None # ignore missing values

	def __confSection(self,conf,section):
		"""returns value of configuration option"""
	        try:
	            return conf.items(section)
	        except ConfigParser.Error:
	            return None	

	def __confGet(self, conf, section, option):
	        """returns the value of the configuration option or None if not set"""
	        try:
	            return conf.get(section, option)
	        except ConfigParser.Error:
	            return None # ignore missing values


	def __setupLogging(self):
	        try:
			"creates and returns file logger"
			logging.config.fileConfig(self.logging_config)
			self.logger = logging.getLogger(self.app_name)
			#self.logger_syslog = logging.getLogger(app_name)
			try:
				self.logger.setLevel(int(self.log_level))
		                #self.logger_syslog.setLevel(int(self.log_level))
			except:
				self.logger.warn("Bad value for option log_level: %s", self.log_level)
				#self.logger_syslog.warn("Bad value for option log_level: %s", self.log_level)
		except Exception, info:
			print "An error is encounted in setting up logger-%s" %info
			sys.exit(1)

	def usage(self):
		"prints the command line options of the program"
	        print """
	                usage:""", os.path.basename(sys.argv[0]), """[options]

	                options:
	                -c file     read main configuration
	                -h          display this help
	             """

	def __parseArgs(self):
	        """parses the command line arguments"""
	        try:
	            opts, args = getopt.getopt(sys.argv[1:], "c:d:l:hn", ["help", "db_commit"])
	        except getopt.GetoptError, exception:
	            print "Error while parsing arguments %s -%s" % (args, str(exception).strip())
	            self.usage()
	            sys.exit(1)

	        for opt, arg in opts:
	            if opt == "-c":
	                self.__readConfig(arg)
	            elif opt == "-h" or opt == "--help":
	                self.usage()
	                sys.exit()

	def setAction(self, act):
	        "define and log what we are doing right now"
	        self.logger.info(act)
	        self.action = act[0].lower() + act[1:]

	def getAction(self):
	        "return the last action"
	        return self.action 
